const md5 = require("md5");
const { loginDao, updateAdminDao } = require("../dao/adminDao");
const { ValidationError } = require("../utils/errors");
const jwt = require("jsonwebtoken");
const { formatResponse } = require("../utils/tool");

// admin 模块的业务逻辑层
module.exports.loginService = async function (loginInfo) {
  loginInfo.loginPwd = md5(loginInfo.loginPwd); // 加密

  let data = await loginDao(loginInfo);

  if (data && data.dataValues) {
    // 添加token
    data = {
      id: data.dataValues.id,
      loginId: data.dataValues.loginId,
      name: data.dataValues.name,
    };

    let loginPeriod = null;
    if (loginInfo.remember) {
      // 用户传了,就用用户的
      loginPeriod = parseInt(loginInfo.remember);
    } else {
      loginPeriod = 1;
    }

    // 生成token
    const token = jwt.sign(data, md5(process.env.JWT_SECRET), {
      expiresIn: 60 * 60 * 24 * loginPeriod,
    });
    console.log(token);

    return {
      token,
      data,
    };
  }
  return {
    data,
  };
};

module.exports.updateAdminService = async function (accountInfo) {
  console.log("====", accountInfo);
  accountInfo.oldLoginPwd = md5(accountInfo.oldLoginPwd); // 加密
  let adminInfo = await loginDao({
    loginId: accountInfo.loginId,
    loginPwd: accountInfo.oldLoginPwd,
  });

  if (adminInfo && adminInfo.dataValues) {
    // 密码正确开始修改
    // 组装一个新的对象开始更新
    let newPassword = md5(accountInfo.loginPwd);
    let newAdminObj = {
      name: accountInfo.name,
      loginId: accountInfo.loginId,
      loginPwd: newPassword,
    };
    const result = await updateAdminDao(newAdminObj);
    console.log("result===>", result);
    return formatResponse(0, "", {
      loginId: accountInfo.loginId,
      name: accountInfo.name,
      id: adminInfo.dataValues.id,
    });
  } else {
    // 密码输入错误,抛出自定义错误
    throw new ValidationError("旧密码不正确");
  }
};
